package top.mengchaob.deploy.service;

import top.mengchaob.deploy.api.DeployServiceI;
import top.mengchaob.deploy.jpa.HostServerRepository;
import top.mengchaob.deploy.table.HostServerDO;
import top.mengchaob.deploy.util.CloseChannel;
import top.mengchaob.deploy.util.SSHUtil;
import top.mengchaob.deploy.util.SftpProgressMonitorImpl;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.mengchaob.fileserver.netty.jpa.FileRepository;
import top.mengchaob.fileserver.netty.table.FileDo;
import top.mengchaob.util.PropUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * @title：
 * @author: mengchaob
 * @date: 2021年04月27日 15:28
 * @description:
 */
@Service
public class DeployService implements DeployServiceI {
    private static Logger logger = LoggerFactory.getLogger(DeployServiceI.class);
    @Autowired
    HostServerRepository hostServerRepository;
    @Autowired
    FileRepository fileRepository;
    @Override
    public void add(HostServerDO hostServerDO) {
        hostServerRepository.saveAndFlush(hostServerDO);
    }

    @Override
    public void del(HostServerDO hostServerDO) {
        hostServerRepository.delete(hostServerDO);
    }

    @Override
    public void delBatchByIds(String ids) {
        String[] ids_ = ids.split(",");
        hostServerRepository.deleteByIds(Arrays.asList(ids_.clone()));
    }

    @Override
    public void update(HostServerDO hostServerDO) {
        hostServerRepository.save(hostServerDO);
    }

    @Override
    public HostServerDO queryById(HostServerDO hostServerDO) {
        Optional optional = hostServerRepository.findById(hostServerDO.getId());
        return (HostServerDO)optional.get();
    }

    @Override
    public List<HostServerDO> queryAll() {
        return hostServerRepository.findAll();
    }

    @Override
    public void deployByFile(String id) {
        ChannelSftp channelSftp = null;
        HostServerDO sshLoginInfo = null;
        Optional optional = hostServerRepository.findById(id);
        if(!optional.isPresent()){
            throw new RuntimeException("当前服务部署信息丢失！");
        }
        sshLoginInfo = (HostServerDO)optional.get();
        DeployShell deployShell = new DeployShell(sshLoginInfo);
        //1.执行前置脚本
        deployShell.preCmd();
        //2.执行上传部署（WebSSH服务直接上传war包、浏览器直接上传war包到ssh服务器）
        try {
            SftpProgressMonitorImpl sftpProgressMonitorImpl = new SftpProgressMonitorImpl();
            channelSftp = SSHUtil.getChannelSftp(sshLoginInfo);
            String fileId = sshLoginInfo.getFileId();
            Optional<FileDo> fileDo = fileRepository.findById(fileId);
            String baseUrl = PropUtil.getV("baseUrl");
            FileDo fd = fileDo.get();
            String suffix = fd.getFileName().substring(fd.getFileName().lastIndexOf("."));
            String filepath = baseUrl+File.separator+fd.getLbCode()+File.separator+fd.getFileId()+suffix;
            File file = new File(filepath);
            InputStream is = new FileInputStream(file);
            channelSftp.connect();
            /**
             * 覆盖模式
             */
            channelSftp.put(is,sshLoginInfo.getFileRemoteAddr(),sftpProgressMonitorImpl, ChannelSftp.OVERWRITE);
            try {
                is.close();
            }catch (Exception e){
                e.printStackTrace();
            }
            CloseChannel.close(channelSftp);
            channelSftp.exit();
            logger.debug("退出上传！");

        } catch (JSchException | SftpException | FileNotFoundException e) {
            e.printStackTrace();
            CloseChannel.close(channelSftp);
            throw new RuntimeException(e.getMessage());
        }
        //3.执行后置脚本，如解压war包，关闭weblogic，启动weblogic等等
        deployShell.afterCmd();
        //4关闭资源
        deployShell.close();
    }

    @Override
    public void deployByGit(String branchCode) {

    }
}
